package com.lyn.module_custom_base.avtivity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

import com.lyn.module_custom_base.dialog.DialogManager;

/**
 * @author:longyongning
 * @date:2021/10/2
 * @description:
 */
public abstract class BaseActivity<T extends ViewBinding> extends AppCompatActivity {

    public T binding;

    public Context context;

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = getBinding();
        setContentView(binding.getRoot());
        context = this;
        setBinding(binding);
        setListener(binding);
        AppManager.getAppManager().addActivity(this);
    }

    public abstract T getBinding();

    public abstract void setBinding(T binding);

    public abstract void setListener(T binding);

    public abstract boolean onBack();


    public void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    public void showProgressBar(String title, String message) {
        if (progressDialog != null) {
            dismissProgressBar();
        }
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle(title);
        progressDialog.setMessage(message);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
    }

    public void dismissProgressBar() {
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }


    /**
     * 跳转新得页面
     *
     * @param newActivity 新的activity
     */
    protected void changeUI(Class newActivity) {
        startActivity(new Intent(getApplicationContext(), newActivity));
    }

    /**
     * 跳转网页
     *
     * @param url
     */
    protected void startToInternet(String url) {
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    }

    /**
     * 跳转传递值
     *
     * @param newActivity 新的activity
     * @param intent
     */
    protected void changeUiWithText(Class newActivity, Intent intent) {
        intent.setClass(getApplicationContext(), newActivity);
        startActivity(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isFinishing()) {
            dismissProgressBar();
            DialogManager.getInstance().dismissAllDialog();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
    }

    @Override
    public void onBackPressed() {
        if (!onBack()){
            super.onBackPressed();
        }
    }
}
